const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : `0${n}`
}


function getDistanceByCoordinate(location_1, location_2) {
	// longitude(经度) and latitude(纬度)
	var lon_1 = location_1.longitude;
	var lat_1 = location_1.latitude;
	var lat_2 = location_2.latitude;
	var lon_2 = location_2.longitude;
	var radEarth = 6378137;

	var radLat1 = (lat_1 * Math.PI) / 180.0;
	var radLat2 = (lat_2 * Math.PI) / 180.0;
	var radLon1 = (lon_1 * Math.PI) / 180.0;
	var radLon2 = (lon_2 * Math.PI) / 180.0;

	var difRadLat = radLat1 - radLat2;
	var difRedLon = radLon1 - radLon2;

	var distance =
			2 *
			Math.asin(
				Math.sqrt(
					Math.pow(Math.sin(difRadLat / 2), 2) +
					Math.cos(radLat1) *
					Math.cos(radLat2) *
					Math.pow(Math.sin(difRedLon / 2), 2)
				)
			);
	distance = distance * radEarth/1000;
	distance = Math.round(distance * 10) / 10;
	return distance; // 返回（km)
}
function compareOrgs(a, b) {
    return a["miles"] - b["miles"]; // 从小到大排序
}
function computeDis(posInfo, orgInfo) {
	var my_location = {
		"longitude": 0,
		"latitude": 0
	}
	if (posInfo && posInfo.longitude && posInfo.latitude) {
		my_location.longitude = posInfo.longitude
		my_location.latitude = posInfo.latitude
	}
	console.log(my_location)
	if (my_location.longitude == 0 || my_location.latitude == 0) {
		for (var i = 0; i < orgInfo.length; i++) {
			for (var j = 0; j < orgInfo[i]["schools"].length; j++) {
				orgInfo[i]["schools"][j]["miles"] = '--'
			}
			orgInfo[i]["miles"] = '--'
		}
		return orgInfo
	}
	for (var i = 0; i < orgInfo.length; i++) {
		var orgMile = 0
		for (var j = 0; j < orgInfo[i]["schools"].length; j++) {
			var curLoc = {
				"longitude": orgInfo[i]["schools"][j]["longitude"],
				"latitude": orgInfo[i]["schools"][j]["latitude"]
			}
			var mile = getDistanceByCoordinate(my_location, curLoc)
			if (orgMile == 0) {
				orgMile = mile
			}
			if (orgMile > mile) {
				orgMile = mile
			}
			orgInfo[i]["schools"][j]["miles"] = mile
		}
		orgInfo[i]["miles"] = orgMile
	}
	orgInfo.sort(compareOrgs)
	console.log(orgInfo)
	return orgInfo
}
function validatePhoneNumber(phoneNumber){
	var pattern =/^1[3456789]\d{9}$/;  
	return pattern.test(phoneNumber);
}
function validateAge(age) {
	if (isNaN(age)) { // 如果输入不是数字则返回false
		return false;
	} else if (age < 0 || age > 20) { // 如果年龄小于0或大于20则返回false
		return false;
	} else {
		return true; // 其他情况都认为年龄正确
	}
}

module.exports = {
	formatTime,
	computeDis, validatePhoneNumber,validateAge
}
